package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.*;
import com.itheima.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.net.HttpCookie;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IShoppingCartService shoppingCartService;

    @Autowired
    private IAddressBookService addressBookService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrdersDetailService ordersDetailService;

    @PostMapping("/submit")
    public R submitOrder(@RequestBody Orders orders, HttpSession session) {
        Long userId = (Long) session.getAttribute("UserId");
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
        List<ShoppingCart> list = shoppingCartService.list(qw);
        // 2、查询用户数据 select * from user where id = ?
        User user = userService.getById(userId);

        // 3、根据地址id查询地址数据 select * from address_book where id = ?
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        // 4、保存订单明细数据：点了哪些菜品或套餐
        long orderId = IdWorker.getId();//订单号
        BigDecimal amount = new BigDecimal(0);
        // ShoppingCart shoppingCart --> OrderDetail orderDetail
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orderId);
            // amount 金额单独设置 数量  *  单价
            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount=amount.add(orderDetail.getAmount());//
            ordersDetailService.updateById(orderDetail);
        }
        orders.setId(orderId);//订单id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(amount);//总金额
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//收货人联系电话
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        ordersService.save(orders);

        // 6、删除当前用户的购物车数据
        // delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(qw1);
        return R.success("交易成功");
    }


    @GetMapping("/userPage")
    public R queryUserPage(Integer page,Integer pageSize,HttpSession session){
        Long userId = (Long) session.getAttribute("UserId");
        Page<Orders> pageInfor = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,userId);
        ordersService.page(pageInfor, qw);
        //列表数据
        List<Orders> records = pageInfor.getRecords();
        //总记录数
        long total = pageInfor.getTotal();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("records", records);
        map.put("total", total);
        return R.success(map);

    }
}
